import { useEffect, useState } from "react";
import { getTableApi, getToken } from "../utils/client";
import { v4 as uuidv4 } from "uuid";
import type { ColumnType } from 'antd/es/table';
import Table from "antd/es/table";

export interface IndexListProps {
    curClientId: string;
    curDatabase: string;
    curTable: string;
}

type Row = string[];

function IndexList(props: IndexListProps) {
    const [columnList, setColumnList] = useState<string[]>([]);
    const [rowList, setRowList] = useState<Row[]>([]);

    const loadIndexList = async () => {
        setColumnList([]);
        setRowList([]);
        const client = getTableApi();
        const res = await client.tableRawQueryPost({
            tableRawQueryPostRequest: {
                id: props.curClientId,
                token: getToken(),
                db: props.curDatabase,
                sql: `SELECT * from pg_indexes WHERE tablename='${props.curTable}'`,
            },
        });
        if (res.columns !== undefined) {
            setColumnList(res.columns.map(item => item.name ?? ""));
        }
        if (res.values !== undefined) {
            const tmpRowList = [] as Row[];
            for (const row of res.values) {
                const tmpList = row.slice();
                tmpList.push(uuidv4());
                tmpRowList.push(tmpList);
            }
            setRowList(tmpRowList);
        }
    };

    const calcCloumnsType = () => {
        return columnList.map((column, index) => ({
            title: column,
            dataIndex: index,
        } as ColumnType<Row>))
    };


    useEffect(() => {
        if (props.curClientId !== "" && props.curDatabase !== "" && props.curTable != "") {
            loadIndexList();
        } else {
            setColumnList([]);
            setRowList([]);
        }
    }, [props.curClientId, props.curDatabase, props.curTable]);

    return (
        <>
            {columnList.length > 0 && (
                <Table rowKey={columnList[0]} columns={calcCloumnsType()} dataSource={rowList} pagination={false} />
            )}
        </>
    );
}

export default IndexList;